﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;

namespace 浏览器客户端.Helper
{
    public class ScannerHook
    {
        public delegate void ScannerDelegate(ScanerCodes codes);
        public event ScannerDelegate ScannerEvent;

        //声明键盘钩子处理的初始值
        private int _hKeyboardHook;
        //13为键盘钩子
        private readonly ScanerCodes _codes = new ScanerCodes();
        //定义成静态，这样不会抛出回收异常
        private static HookProc _hookProc;
        delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        //设置钩子
        private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        //卸载钩子
        private static extern bool UnhookWindowsHookEx(int idHook);
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        //继续下个钩子
        private static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);

        [DllImport("user32", EntryPoint = "GetKeyNameText")]
        private static extern int GetKeyNameText(int param, StringBuilder lpBuffer, int nSize);
        [DllImport("user32", EntryPoint = "GetKeyboardState")]
        //获取按键的状态
        private static extern int GetKeyboardState(byte[] pbKeyState);

        [DllImport("kernel32.dll")]
        //使用WINDOWS API函数代替获取当前实例的函数,防止钩子失效
        public static extern IntPtr GetModuleHandle(string name);

        public bool Start()
        {
            if (_hKeyboardHook == 0)
            {
                _hookProc = KeyboardHookProc;
                //GetModuleHandle 函数 替代 Marshal.GetHINSTANCE  
                //防止在 framework4.0中 注册钩子不成功  
                IntPtr modulePtr = GetModuleHandle(Process.GetCurrentProcess().MainModule?.ModuleName);
                //WH_KEYBOARD_LL=13  
                //全局钩子 WH_KEYBOARD_LL  
                //  hKeyboardHook = SetWindowsHookEx(13, hookproc, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);  
                _hKeyboardHook = SetWindowsHookEx(13, _hookProc, modulePtr, 0);
            }
            return _hKeyboardHook != 0;
        }
        public bool Stop()
        {
            if (_hKeyboardHook != 0)
            {
                bool retKeyboard = UnhookWindowsHookEx(_hKeyboardHook);
                _hKeyboardHook = 0;
                return retKeyboard;

            }
            return true;
        }
        private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
        {


            EventMsg msg = (EventMsg)Marshal.PtrToStructure(lParam, typeof(EventMsg));
            _codes.Add(msg);
            if (ScannerEvent != null && msg.Message == 13 && msg.ParamH > 0 && !string.IsNullOrEmpty(_codes.Result))
            {
                ScannerEvent(_codes);
            }
            return CallNextHookEx(_hKeyboardHook, nCode, wParam, lParam);
        }
        public class ScanerCodes
        {
            private int ts = 100; // 指定输入间隔为300毫秒以内时为连续输入  
            private readonly List<List<EventMsg>> _keys = new List<List<EventMsg>>();
            private readonly List<int> _keydown = new List<int>();   // 保存组合键状态  
            private readonly List<string> _result = new List<string>();  // 返回结果集  
            private DateTime _last = DateTime.Now;
            private readonly byte[] _state = new byte[256];
            private string _key = string.Empty;
            private string _cur = string.Empty;
            public EventMsg Event
            {
                get
                {
                    if (_keys.Count == 0)
                    {
                        return new EventMsg();
                    }
                    else
                    {
                        return _keys[_keys.Count - 1][_keys[_keys.Count - 1].Count - 1];
                    }
                }
            }

            public string Result
            {
                get
                {
                    if (_result.Count > 0)
                    {
                        return _result[_result.Count - 1].Trim();
                    }
                    else
                    {
                        return null;
                    }
                }
            }

            public bool IsShift => _keydown.Contains(160);

            public void Add(EventMsg msg)
            {
                #region 记录按键信息           

                // 首次按下按键  
                if (_keys.Count == 0)
                {
                    _keys.Add(new List<EventMsg>());
                    _keys[0].Add(msg);
                    _result.Add(string.Empty);
                }
                // 未释放其他按键时按下按键  
                else if (_keydown.Count > 0)
                {
                    _keys[_keys.Count - 1].Add(msg);
                }
                // 单位时间内按下按键  
                else if ((DateTime.Now - _last).TotalMilliseconds < ts)
                {
                    _keys[_keys.Count - 1].Add(msg);
                }
                // 从新记录输入内容  
                else
                {
                    _keys.Add(new List<EventMsg>());
                    _keys[_keys.Count - 1].Add(msg);
                    _result.Add(string.Empty);
                }
                #endregion
                _last = DateTime.Now;
                #region 获取键盘状态
                // 记录正在按下的按键  
                if (msg.ParamH == 0 && !_keydown.Contains(msg.Message))
                {
                    _keydown.Add(msg.Message);
                }
                // 清除已松开的按键  
                if (msg.ParamH > 0 && _keydown.Contains(msg.Message))
                {
                    _keydown.Remove(msg.Message);
                }
                #endregion
                #region 计算按键信息

                int c = msg.ParamL & 0xff;
                StringBuilder strKeyName = new StringBuilder(500);
                if (GetKeyNameText(c * 65536, strKeyName, 255) > 0)
                {
                    _key = strKeyName.ToString().Trim(new char[] { ' ', '\0' });
                    GetKeyboardState(_state);
                    if (_key.Length == 1 && msg.ParamH == 0)// && msg.paramH == 0
                    {
                        // 根据键盘状态和shift缓存判断输出字符  
                        _cur = ShiftChar(_key, IsShift, _state).ToString();
                        _result[_result.Count - 1] += _cur;
                    }
                    // 备选
                    else
                    {
                        _cur = string.Empty;
                    }
                }
                #endregion
            }
            private char ShiftChar(string k, bool isShiftDown, byte[] state)
            {
                bool capsLock = state[0x14] == 1;
                char chr = (capsLock ? k.ToUpper() : k.ToLower()).ToCharArray()[0];
                if (isShiftDown)
                {
                    if (chr >= 'a' && chr <= 'z')
                    {
                        chr = (char)(chr - 32);
                    }
                    else if (chr >= 'A' && chr <= 'Z')
                    {
                        if (chr == 'Z')
                        {

                        }
                        chr = (char)(chr + 32);
                    }
                    else
                    {
                        string s = "`1234567890-=[];',./";
                        string u = "~!@#$%^&*()_+{}:\"<>?";
                        if (s.IndexOf(chr) >= 0)
                        {
                            return (u.ToCharArray())[s.IndexOf(chr)];
                        }
                    }
                }
                return chr;
            }
        }
        public struct EventMsg
        {
            public int Message;
            public int ParamL;
            public int ParamH;
        }
    }
}

